package com.twu.biblioteca.service;

import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.twu.biblioteca.Library.Movie;

import java.security.InvalidParameterException;
import java.util.List;

import static com.google.common.collect.FluentIterable.from;

public class MovieService {

    private List<Movie> movies;

    public MovieService(List<Movie> movies) {
         this.movies = movies;
    }

    public List<Movie> getMovies() {
        return movies;
    }

    public List<Movie> getAvailableMovies() {
        return from(movies).filter(new Predicate<Movie>() {
            @Override
            public boolean apply(Movie movie) {
                return movie.isAvailable();
            }
        }).toList();
    }

    public List<String> getMovieNames(List<Movie> movies) {
        return from(movies).transform(new Function<Movie, String>() {
            @Override
            public String apply(Movie movie) {
                return movie.getName();
            }
        }).toList();
    }

    public void checkOutMovie(String bookName, String userName) throws InvalidParameterException{
        Movie movie = findMovieByName(bookName);
        movie.setAvailable(false);
        movie.setBorrower(userName);
    }

    public Movie findMovieByName(final String movieName) {
        Movie movie;
        try {
            movie = from(getAvailableMovies()).firstMatch(new Predicate<Movie>() {
                @Override
                public boolean apply(Movie movie) {
                    return movieName.equals(movie.getName());
                }
            }).get();
        } catch (Exception e) {
            throw new InvalidParameterException();
        }
        return movie;
    }

}
